<?php

class PostsController extends AppController {

    var $name = 'Posts';
    var $components = array('Session');
    var $helpers = array('Js');

    function index() {
        
       
//        $this->set('current_user',  $this->Auth->user('name'));
        $this->set('posts', $this->Post->find('all', array('contain' => 'Tag')));
        $this->set('cows', $this->params['url']);
    }

    function sechungpark(&$com, $id, $sort="Comment.Created") {
        foreach ($com as &$com1) {
            $com1['Comment']['replies'] = $this->Post->Comment->find('all', array('conditions' => array('Comment.post_id' => $id, 'parent_id' => $com1['Comment']['id']), 'order' => array($sort . ' DESC'), 'fields' => array('Comment.text', 'Comment.id', 'Comment.name', 'Comment.email', 'Comment.up', 'Comment.down', 'Comment.anonid')));
            if (count($com1['Comment']['replies']) > 0)
                $this->sechungpark($com1['Comment']['replies'], $id);
            else
                unset($com1['Comment']['replies']);
        }
    }

//        function tagem($id=null)
//            {
//                if (!empty($this->data)) {
//			// get the tags from the textarea data
//			$tags = explode(' ',$this->data['Post']['tags']);
//			foreach($tags as $_tag) {
//				$_tag = strtolower(trim($_tag));
//				if ($_tag) {
//					$this->Post->Tag->recursive = -1;
//					$tag = $this->Post->Tag->findByName($_tag);
//					if (!$tag) {
//						$this->Post->Tag->create();
//						$tag = $this->Post->Tag->save(array('name'=>$_tag));
//						$tag['Tag']['id'] = $this->Post->Tag->id;
//						if (!$tag) {
//							$this->_flash(__(sprintf('The Tag %s could not be saved.',$_tag), true),'success');
//						}
//					}
//					if ($tag) {
//						$this->data['Tag']['Tag'][$tag['Tag']['id']] = $tag['Tag']['id'];
//					}
//				}
//			}
//
//			// save the data
//			$this->Post->create();
//			if ($this->Post->save($this->data)) {
//				$this->Session->setFlash(__('The Post has been saved.', true));
//				$this->redirect(array('action'=>'form',$this->Post->id));
//			}
//			else {
//				$this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));
//			}
//		}
//		if (empty($this->data)) {
//			$this->data = $this->Post->read(null, $id);
//			// load the habtm data for the textarea
//			$tags = array();
//			if (isset($this->data['Tag']) && !empty($this->data['Tag'])) {
//				foreach($this->data['Tag'] as $tag) {
//					$tags[] = $tag['name'];
//				}
//				$this->data['Post']['tags'] = implode(', ',$tags);
//			}
//		}
//		
//		// get the posts current tags
//		$post = $id ? $this->Post->find(array('Post.id'=>$id)) : false;
//		
//		$this->set(compact('post'));
//            }
    function view($id) {
        $this->Post->id = $id;
        $post = $this->Post->read();
        $this->set('post', $post);
//                foreach ($post as $comment)
//                    {
//                    
//                    }
        $com = $this->Post->Comment->find('all', array('conditions' => array('Comment.post_id' => $id, 'parent_id' => 0), 'order' => array('Comment.created DESC'), 'fields' => array('Comment.text', 'Comment.id', 'Comment.name', 'Comment.email', 'Comment.up', 'Comment.down', 'Comment.anonid')));

        $this->sechungpark($com, $id);
        if ($this->Session->check('username'))
            $this->set('username',$this->Session->read('username'));
//   $this->set('username', this->Session->read('username'));
        $this->set('com', $com);
//                $stuff = $this->Post->read();
//                $this->Session->setFlash($stuff['Post']['title']);
    }

//        function onChange($id=null)
//         {
//            $this->autoRender = $this->layout = false; 
//         }
    function onchange($id=null, $sort="Comment.Created", $newcom="") {
        $this->layout = "none";
        $com = $this->Post->Comment->find('all', array('conditions' => array('Comment.post_id' => $id, 'parent_id' => 0), 'order' => array($sort . ' DESC'), 'fields' => array('Comment.text', 'Comment.id', 'Comment.name', 'Comment.email', 'Comment.up', 'Comment.down', 'Comment.anonid')));
        $this->sechungpark($com, $id);
              if ($this->Session->check('username'))
            $this->set('username',$this->Session->read('username'));
        $this->set('com', $com);
        $this->set('newcom', $newcom);
    }

    function add() {
        if (!empty($this->data)) {
            if ($this->Post->saveAll($this->data)) {
                $this->Session->setFlash('Your post has been added to the General Board');
                $this->redirect(array('action' => '../boards/index'));
            }
        }
    }

//        function add1($post_id = null) {
//           if(!empty($this->data)) {
//              //Use the following to avoid   validation errors:
//              unset($this->Post->Comment->validate['post_id']);
//              
//              $this->Post->saveAll($this->data, array('validate' => 'first'));
//              $this->Session->setFlash('POSTED');
//              $this->redirect(array('action' => '../posts/index'));
//           }
//        }


    function delete($id) {
        if ($this->Post->delete($id)) {

            $this->Session->setFlash('The post with id: ' . $id . ' has been deleted.');
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash('The post with id: ' . $id . ' has <i>NOT</i> been deleted.');
            $this->redirect(array('action' => 'index'));
        }
    }

    function edit($id = null) {
        $this->Post->id = $id;
        if (empty($this->data)) {
            $this->Session->setFlash('You are editing a post!.');
            $this->data = $this->Post->read();
        } else {
            if ($this->Post->save($this->data)) {
                $this->Session->setFlash('Your post has been updated.');
                $this->redirect(array('action' => 'index'));
            }
        }
    }
   

    function search($search='') {
       
        $conditions = array();
        $conditions1 = array();
        $conditions2 = array();
        $othersearch = "";
//            if  (isset($this->params['url']['disinclude'])) {
//                $this->params['url']['disinclude']=" ".$this->params['url']['disinclude'];
//                $othersearch.=str_replace(" ", " -",   $this->params['url']['disinclude']);
////                $this->params['url']['disinclude'];
//                }
//            $this->params['url']['any']=str_replace(" ", " +",   $this->params['url']['any']);

        $search = $this->params['url']['search'] . $othersearch;
        if (!isset($this->params['url']['p']) && !isset($this->params['url']['c']) && !isset($this->params['url']['i'])) {
            $this->params['url']['p'] = true;
            $this->params['url']['c'] = true;
            $this->params['url']['i'] = true;
        }
        $this->set('p', isset($this->params['url']['p']));
        $this->set('c', isset($this->params['url']['c']));
        $this->set('i', isset($this->params['url']['i']));
        if (!isset($this->params['url']['sort']) || $this->params['url']['sort'] == "")
            $sort = "created";
        else
            $sort = $this->params['url']['sort'];
//            if ($sort=='up')
//                $sort1='Top';
//            else if ($sort== 'created')
//                $sort1='Recently Modified';
//            else if ($sort == 'replies')
//                $sort1='Number of replies';
//            
        $this->set('sort', $sort);
        if (isset($this->params['url']['advanced']))
            $this->set('advanced', true);
        if (isset($this->params['url']['viewas']) && $this->params['url']['viewas'] == 1)
            $this->set('viewas', 1);
        else
            $this->set('viewas', 0);
        $m = "";
        $str = $search;
        preg_match('/"([^"]+)"/', $str, $m);
        $x = 0;
        if (count($m) > 0) {
            $search = str_replace($m[0], '', $search);
            $searchtext = explode(" ", $m[1]);
            foreach ($searchtext as $text) {
//                    'AND'][$x
//                    'AND'][$x
                if (isset($this->params['url']['p'])) {
                    $conditions[$x]['OR'][] = array("Post.title LIKE" => "%" . $text . "%");
                    $conditions[$x]['OR'][] = array("Post.body LIKE" => "%" . $text . "%");
                }
                if (isset($this->params['url']['c'])) {
                    $conditions1[$x]['OR'][] = array("Comment.name LIKE" => "%" . $text . "%");
                    $conditions1[$x]['OR'][] = array("Comment.text LIKE" => "%" . $text . "%");
                }
                $x++;
            }
        }
        $searchtags = explode(" ", $search);
        $y = 0;
        $not_tag=array();
        if ($search != "") {
            $greaterthan=true;
            $lessthan=true;
            $author=true;
            foreach ($searchtags as $tag) {
                if ($tag != "") {
                    if (strpos($tag, "author:") !== false && $author) {
                        $author=false;
                        $tag = str_replace("author:", '', $tag);
                        if (isset($this->params['url']['p']))
                            $conditions[] = array("Post.name" => $tag);
                        if (isset($this->params['url']['c']))
                            $conditions1[] = array("Comment.name" => $tag);
                    }
                    else if (strpos($tag, "lessthan:") !== false && $lessthan) {
                        $lessthan=false;
                        $tag = str_replace("lessthan:", '', $tag);
                        if (isset($this->params['url']['p']))
                            $conditions[] = array("CHAR_LENGTH(Post.body) <" => $tag);
                        if (isset($this->params['url']['c']))
                            $conditions1[] = array("CHAR_LENGTH(Comment.text) <" => $tag);
                    }
                    else if (strpos($tag, "greaterthan:") !== false && $greaterthan) {
                        $greaterthan=false;
                        $tag = str_replace("greaterthan:", '', $tag);
                        if (isset($this->params['url']['p']))
                            $conditions[] = array("CHAR_LENGTH(Post.body) >" => $tag);
                        if (isset($this->params['url']['c']))
                            $conditions1[] = array("CHAR_LENGTH(Comment.text) >" => $tag);
                    }
                    
                    else {
                        if (strpos($tag, '-') !== 0) {
                            $conditions['Tag.tag'][]=$tag;
                            $conditions1["Tag.tag"][] = $tag;
                            $y++;
                        } else {
                            $not_tag[] = substr($tag, 1);
                        }
                    }
//                            $conditions1['AND'][$x]= array("Comment.name LIKE" => "%".$text."%");
                    $x++;
                }
            }
        }
   
        $flashmessage = 'Searching for ';
        if ($search != "") {
            $flashmessage.= 'tags: <b>"' . $search . '"</b> ';
            if (isset($m[1]))
                $flashmessage.='and ';
        }
        if (isset($m[1]))
            $flashmessage.='text: <b>"' . $m[1] . '"</b>.';
        if (!isset($this->params['url']['p']) || !isset($this->params['url']['c']) || !isset($this->params['url']['i'])) {
            $flashmessage.='; not including: "';
            if (!isset($this->params['url']['p']))
                $flashmessage.="<i>posts</i> ";
            if (!isset($this->params['url']['c']))
                $flashmessage.="<i>comments</i> ";
            if (!isset($this->params['url']['i']))
                $flashmessage.="<i>images</i> ";
            $flashmessage.='"';
        }
        $this->Session->setFlash($flashmessage);
//            $conditions=    array("Post.title LIKE" => "%".$search."%");
//            
//            
//            $conditions=     array(    'OR' => array(    array("Post.title LIKE" => "%".$search."%"),    array("Post.body LIKE" => "%".$search."%")    ));
//            $conditions1=     array(    'OR' => array(    array("Comment.name LIKE" => "%".$search."%"),    array("Comment.text LIKE" => "%".$search."%")    ));    

        $this->set('searchBar', true);

        $this->set('search1', $conditions2);
//         $conditions['OR'][]= (array("Post.title LIKE" => "%".$search."%"),    array("Post.body LIKE" => "%".$search."%"));
//             $conditions=array(
//                   
//                        'Post.title' =>$search
//                    
//                );
        //recursive
        //
            //


//$com=$this->Post->find('all', array(
//    'conditions'=>array('Tag.tag'=>'who') ,
//  'contain'=>'Tag' //
//    
//));

        if (count($searchtags) > 0) {
//            if (isset($this->params['url']['p']))
//                $com = $this->Post->find('all', array('conditions' => $conditions, 'order' => array('Post.' . $sort . ' DESC'), 'contain' => array('Tag' => array('conditions' => $conditions2))));
//            if (isset($this->params['url']['c']))
//                $com1 = $this->Post->Comment->find('all', array('conditions' => $conditions1, 'order' => array('Comment.' . $sort . ' DESC'), 'contain' => array('Tag' => array('conditions' => $conditions2))));
//     $com = $this->Post->find('all', array('conditions' => $conditions, 'order' => array('Post.' . $sort . ' DESC'), 'contain' => array('Tag' => array('conditions' => $conditions2))));

            
            
          $options['contain']='Tag';
//          $conditions['Tag.tag'][]='who';
          $options['conditions']=$conditions;
          // IF ONLY THERE WAS A WAY TO COMBINE THIS INTO ONE MYSQL COMMAND.
          if (isset($this->params['url']['p'])) {
              $options['order']= array('Post.' . $sort . ' DESC');
              if (isset($conditions['Tag.tag']))
               {
                       $options['joins'] = array(
            array('table' => 'posts_tags',
                    'alias' => 'PostsTag',
                    'type' => 'inner',
                    'conditions' => array(
                            'Post.id =PostsTag.post_id'
                    )
            ),
            array('table' => 'tags',
                    'alias' => 'Tag',
                    'type' => 'inner',
                    'conditions' => array(
                            'PostsTag.tag_id = Tag.id'
                    )
            ));              
              $options['fields']=array('Post.id','Post.title', 'Post.up', 'Post.down', 'Post.created','Post.body', 'Post.name');
              $options['group'] = array('Post.id', 'Post.title HAVING COUNT(*) = '.$y );
              }
    //          $option['group']= array('Post.id','Post.title HAVING COUNT(*) = '.$y);
    //          $option['group']=array('Post.id','Post.title HAVING COUNT(*) <= '.$y);
              $com = $this->Post->find('all', $options);
              if (count($not_tag) > 0) {
                $com=$this->filterCom($com,$not_tag);
                 $this->set('flag','test');
    //            unset($com);
                }
          }
          
         if (isset($this->params['url']['c'])) {
             $options['conditions']=$conditions1;
              $options['order']= array('Comment.' . $sort . ' DESC');
              if (isset($conditions['Tag.tag']))
               {
                $options['joins'] = array(
                array('table' => 'comments_tags',
                        'alias' => 'CommentsTag',
                        'type' => 'inner',
                        'conditions' => array(
                                'Comment.id =CommentsTag.comment_id'
                        )
                ),
                array('table' => 'tags',
                        'alias' => 'Tag',
                        'type' => 'inner',
                        'conditions' => array(
                                'CommentsTag.tag_id = Tag.id'
                        )
                ));              
                  $options['fields']=array('Comment.id','Comment.name','Comment.post_id', 'Comment.text','Comment.up', 'Comment.down','Comment.anonid','Comment.created');
                  $options['group'] = array('Comment.id', 'Comment.name HAVING COUNT(*) = '.$y );
                  }
        //          $option['group']= array('Post.id','Post.title HAVING COUNT(*) = '.$y);
        //          $option['group']=array('Post.id','Post.title HAVING COUNT(*) <= '.$y);
                  $com1 = $this->Post->Comment->find('all', $options);
                  if (count($not_tag) > 0) {
                    $com1=$this->filterCom($com1,$not_tag);
                     $this->set('flag','test');
        //            unset($com);
                    }
          }

          
//            if (isset($this->params['url']['p'])) {
//                $this->filterComment($com, "Post", $y);
//                $this->set('search1', $com);
//            }
//            if (isset($this->params['url']['c']))
//                $this->filterComment($com1, "Comment", $y);
        }
        else {
            if (isset($this->params['url']['p']))
                $com = $this->Post->find('all', array('conditions' => $conditions, 'contain' => 'Tag'));
            if (isset($this->params['url']['c']))
                $com1 = $this->Post->Comment->find('all', array('conditions' => $conditions1, 'contain' => 'Tag'));
        }
//          $com2= $this->Post->find('all',array('conditions' => $sconditions, 'contain'=>'Tag'));
//            $com= $this->Post->find('all', array('conditions' => $conditions, 'contain' => 'Tag.tag="who"'));
//            $com1= $this->Post->Comment->find('all', array('conditions' => $conditions1,  'recursive' => '-1'));
//           
        //array('Tag' => array ('conditions'=>$conditions2)))
//        if (isset($this->params['url']['p']) && isset($this->params['url']['c']))
//            $com = array_merge($com, $com1);
//        else if (!isset($this->params['url']['p']))
//            $com = $com1;
//                $com=$com1;
// 'Tag.tag="who"'
//        $this->set('search', $com);
//            urldecode($this->params['url']['search']))
                      
//           $this->set('search1',$com);
        
          if (isset($this->params['url']['c']) && isset($this->params['url']['p']))
             $com=array_merge($com,$com1);
          else if (!isset($this->params['url']['p']))
             $com=$com1;
          
          
//          usort($com, 'sortByDate');
          if ($sort=="created")
             usort($com, array($this, 'sortByCreated'));
          else
              usort($com, array($this, 'sortByTop'));
          $this->set('search1',$com);
        
           $this->set('search', $com);
         
        $this->set('search2', $this->params['url']['search']);
//            $this->redirect(array('action' => 'index'));
    }
    
    
      function filterCom($com, $not_tag) {
        $com1=array();
        
        foreach ($com as $value)  {
            $add=true;
            foreach ($value['Tag'] as $value1) {
                if (isset($value1['tag']))
                    if (in_array($value1['tag'], $not_tag)) 
                           $add=false; 
                    }
                    if ($add)
                        $com1[]=$value;
               }
        return $com1;
    }
    
    function sortByCreated($a, $b) {
        
        $value="";
        $value1="";
        if (isset($a['Comment']))
              $value=$a['Comment']['created'];
        else
              $value=$a['Post']['created'];
        if (isset($b['Comment']))
              $value1=$b['Comment']['created'];
        else
              $value1=$b['Post']['created'];
        $value=strtotime($value);
        $value1=strtotime($value1);
         if ($value == $value1) return 0;
         return ($value > $value1) ? -1 : 1;
        }
    function sortByTop($a, $b) {
        
        $value="";
        $value1="";
        if (isset($a['Comment']))
              $value=$a['Comment']['up'];
        else
              $value=$a['Post']['up'];
        if (isset($b['Comment']))
              $value1=$b['Comment']['up'];
        else
              $value1=$b['Post']['up'];
         if ($value == $value1) return 0;
         return ($value > $value1) ? -1 : 1;
        }
        
        
}      

?>